package com.example.springsecurity.service.impl;

import com.example.springsecurity.domain.*;
import com.example.springsecurity.mapper.ChoiceQuestionMapper;
import com.example.springsecurity.mapper.ExperimentMapper;
import com.example.springsecurity.service.ExperimentService;
import com.example.springsecurity.utils.FileUploadAndDownload;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.excel.ExcelUtils;
import com.example.springsecurity.utils.redis.RedisCache;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@Service
public class ExperimentServiceImpl implements ExperimentService {


    @Autowired
    public ExperimentMapper experimentMapper;

    @Autowired
    public ChoiceQuestionMapper choiceQuestionMapper;


    @Autowired
    public RedisCache redisCache;



    private static Logger logger= LoggerFactory.getLogger(ExperimentServiceImpl.class);

   @Autowired
   private FileUploadAndDownload fileUploadAndDownload;


    @Override
    public ResultBean addExperiment(Project project, MultipartFile file) {
        if(project.getExperimentKind()!=1){
            String filePath=fileUploadAndDownload.upload(file);
            if(StringUtils.isNotEmpty(filePath)){
                String fileName=file.getOriginalFilename();
                project.setFilePath(filePath);
                project.setFileName(fileName);
            }
        }
        logger.info("项目实验{}",project);
        Integer addExperimentCount=experimentMapper.addExperiment(project);
//        ResultBean resultBean=new ResultBean();
        if(addExperimentCount!=0){
            return ResultBean.success("成功添加项目！");
        }else{return ResultBean.error("添加失败！");}

    }


    @Override
    public ResultBean searchExperiment(Integer pageNum, Integer pageSize, String projectName) {
        PageHelper.startPage(pageNum, pageSize);
        List<Project> projectList=experimentMapper.searchExperiment(projectName);
        projectList.forEach(project -> {
            Integer checkAssignStatus=experimentMapper.checkAssignStatus(project.getProjectId());
            if(checkAssignStatus!=0){
                project.setAssignStatus(1);
            }else{
                project.setAssignStatus(0);
            }
        });
        PageInfo<Project> projectPageInfo=new PageInfo<>(projectList);
        ResultBean resultBean = new ResultBean();
        resultBean.put("data",projectPageInfo);
        resultBean.put("code",200);
        return resultBean;
    }


    @Override
    public ResultBean updateProject(Project project, MultipartFile file) {
        if(file!=null){
            String filePath=fileUploadAndDownload.upload(file);
            if(StringUtils.isNotEmpty(filePath)){
                String fileName=file.getOriginalFilename();
                project.setFilePath(filePath);
                project.setFileName(fileName);
            }
        }
        logger.info("修改项目信息{}",project);
        if(project.isWhetherOpen()){
            experimentMapper.deleteProjectShareTeacher(project.getProjectId());//删除项目共享表中原项目的共享教师编号
        }
        Integer updateProjectStatus=experimentMapper.updateProject(project);
        if(updateProjectStatus!=0){
            return ResultBean.success("修改成功！");
        }else{
            return ResultBean.error("修改失败！");
        }
    }

    @Override
    public ResultBean searchArrangementProject(Integer pageNum, Integer pageSize, Integer collegeId, Integer majorId, String projectName) {
        PageHelper.startPage(pageNum,pageSize);
        List<RoProject> projectList=experimentMapper.searchArrangementProject(collegeId,majorId,projectName);
        PageInfo projectPageInfo=new PageInfo(projectList);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",projectPageInfo);
        resultBean.put("code",200);
        return resultBean;
    }


    @Override
    public ResultBean arrangementProject(Project project) {
        Integer arrangementProjectStatus=experimentMapper.arrangementProject(project);
        if(arrangementProjectStatus!=0){
            return ResultBean.success("操作成功");
        }else {
            return ResultBean.error("操作失败失败");
        }
    }


    @Override
    public void exportProject(HttpServletRequest request, HttpServletResponse response) {
        List<RoProject> projectList=experimentMapper.exportProject();
        ExcelUtils excelUtils=new ExcelUtils();
        excelUtils.cooperationData(request,response,projectList,"实验项目表",RoProject.class);
    }

    @Override
    public ResultBean searchProjectMaintenance(Integer pageNum, Integer pageSize, String projectName,Integer userId) {
        PageHelper.startPage(pageNum,pageSize);
        logger.info("实验名称{}",projectName);
        List<RoProject> roProjectList=experimentMapper.searchProjectMaintenance(projectName,userId);
        PageInfo pageInfo=new PageInfo(roProjectList);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",pageInfo);
        resultBean.put("code",200);
        return resultBean;
    }


    @Override
    public ResultBean getProjectMaintenanceDetail(Integer projectId) {
        RoProject roProject=experimentMapper.getProjectMaintenanceDetail(projectId);
        List<ProjectShare> projectShareList=experimentMapper.getProjectShare(projectId);
        List<ProjectTeach> projectTeachList=experimentMapper.getProjectTeach(projectId);
        projectShareList.forEach(projectShare -> {
            SysUser sysUser=experimentMapper.getUsername(projectShare.getShareTeacherId());
            projectShare.setShareTeacherName(sysUser.getRealName());
        });
        projectTeachList.forEach(projectTeach -> {
            SysUser sysUser=experimentMapper.getUsername(projectTeach.getProjectTeacherId());
            projectTeach.setProjectTeacherName(sysUser.getRealName());
        });
        ShareTeachResult shareTeachResult=new ShareTeachResult();
        shareTeachResult.setProject(roProject);
        shareTeachResult.setProjectShareList(projectShareList);
        shareTeachResult.setProjectTeachList(projectTeachList);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",shareTeachResult);
        resultBean.put("code",200);
        return resultBean;
    }

    @Override
    public ResultBean editProjectMaintenance(Project project, MultipartFile file,Integer[] shareTeacherIds,Integer[] projectTeaIds) {
        if(null!=file){
          String cover=fileUploadAndDownload.upload(file);
          project.setCover(cover);
        }
        if(shareTeacherIds.length!=0){
            experimentMapper.deleteProjectShareTeacher(project.getProjectId());//删除项目共享表中原项目的共享教师编号
            for (int i = 0; i < shareTeacherIds.length; i++) {
                ProjectShare projectShare=new ProjectShare();
                projectShare.setShareProjectId(project.getProjectId());
                projectShare.setShareTeacherId(shareTeacherIds[i]);
                experimentMapper.insertShareProject(projectShare);//添加项目共享教师编号接口
            }
        }
        if(projectTeaIds.length!=0){
            experimentMapper.deleteProjectTeacher(project.getProjectId());//删除项目表中的原项目有关教师编号
            for (int i = 0; i < projectTeaIds.length; i++) {
                ProjectTeach projectTeach=new ProjectTeach();
                projectTeach.setProjectTeacherId(projectTeaIds[i]);
                projectTeach.setProjectId(project.getProjectId());
                experimentMapper.insertTeachProject(projectTeach);//添加项目教学教师编号接口
            }
        }
        Integer editProjectMaintenanceStatus=experimentMapper.editProjectMaintenance(project);
        if(editProjectMaintenanceStatus!=0){
            return ResultBean.success("修改成功");
        }else{
            return ResultBean.error("修改失败");
        }
    }


    @Override
    public ResultBean editProjectVideo(Video video, MultipartFile file) {
        if(file!=null){
            String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            if(!("mp4".equalsIgnoreCase(suffix))){
                return ResultBean.error("请上传mp4格式的文件");
            }
            String videoPath=fileUploadAndDownload.upload(file);
            video.setVideoPath(videoPath);
        }
        experimentMapper.deleteProjectVideoByProjectId(video.getVideoProjectId());//上传项目观看视频的前提操作是先将项目之前有关的视频文件给删除；
       Integer editProjectVideoStatus=experimentMapper.editProjectVideo(video);
        if(editProjectVideoStatus!=0){
            return ResultBean.success("成功上传视频！");
        }else{
            return ResultBean.error("上传视频失败！");
        }
    }


    @Override
    public ResultBean getProjectVideo(Integer projectId) {
        List<Video> videoList=experimentMapper.getProjectVideo(projectId);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",videoList);
        resultBean.put("code",200);
        return resultBean;
    }

    @Override
    public ResultBean deleteProjectVideo(Integer videoId) {
        Integer deleteProjectVideoStatus=experimentMapper.deleteProjectVideo(videoId);
        logger.info("删除视频",deleteProjectVideoStatus);
        if(deleteProjectVideoStatus!=0){
            return ResultBean.success("成功删除该视频资料！");
        }else{
            return ResultBean.error("失败删除该视频资料！");
        }
    }


    @Override
    public ResultBean updateProjectVideo(Video video, MultipartFile file) {
        if(null!=file){
            String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            if(!("mp4".equalsIgnoreCase(suffix))){
                return ResultBean.error("请上传mp4格式的文件");
            }
            String videoPath=fileUploadAndDownload.upload(file);
            video.setVideoPath(videoPath);
        }
        Integer updateProjectVideoStatus=experimentMapper.updateProjectVideo(video);
        if(updateProjectVideoStatus!=0){
            return ResultBean.success("成功修改视频有关信息！");
        }else{
            return ResultBean.error("修改视频信息失败！");
        }
    }

    @Override
    public ResultBean uploadProjectLearn(LearnMaterials learnMaterials, MultipartFile file) {
        Integer materialsCategory=3;
        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        if("jpg".equalsIgnoreCase(suffix)||"png".equalsIgnoreCase(suffix)){
            materialsCategory=2;
        }else if("mp3".equalsIgnoreCase(suffix)||"mp4".equalsIgnoreCase(suffix)){
            materialsCategory=1;
        }
        learnMaterials.setMaterialsName(file.getOriginalFilename());
        learnMaterials.setMaterialsCategory(materialsCategory);
        String materialsPath=fileUploadAndDownload.upload(file);
        learnMaterials.setMaterialsPath(materialsPath);
        Integer uploadProjectLearnStatus=experimentMapper.uploadProjectLearn(learnMaterials);
        if(uploadProjectLearnStatus!=0){
            return ResultBean.success("成功上传资料");
        }else{
            return ResultBean.error("上传资料失败");
        }
    }

    @Override
    public ResultBean getProjectLearnMaterials(Integer projectId) {
        List<LearnMaterials> learnMaterialsList=experimentMapper.getProjectLearnMaterials(projectId);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",learnMaterialsList);
        resultBean.put("code",200);
        return resultBean;
    }


    @Override
    public void downloadProjectLearnMaterials(Integer learnId,HttpServletRequest request, HttpServletResponse response) {
        String materialsPath=experimentMapper.downloadProjectLearnMaterials(learnId);
        try {
            fileUploadAndDownload.download(request,response,materialsPath);
            logger.info("下载成功{}",materialsPath);
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("下载失败{}",materialsPath);
        }
    }


    @Override
    public ResultBean editProjectReport(Project project) {
        Integer editProjectReport=experimentMapper.editProjectReport(project);
        if(editProjectReport!=0){
            return ResultBean.success("成功修改实验报告");
        }else{
            return ResultBean.error("修改实验报告失败");
        }
    }

    @Override
    public ResultBean getProjectReport(Integer projectId) {
        Project project=experimentMapper.getProjectReport(projectId);
        ResultBean resultBean=new ResultBean();
        resultBean.put("data",project);
        resultBean.put("code",200);
        return resultBean;
    }



    @Override
    public ResultBean getProject(Integer projectId) {
       RoProject project=experimentMapper.getProject(projectId);
        return ResultBean.success(project);
    }
    /**
     * 根据实验项目的id获取到布置实验时所展示的实验内容
     * @param projectId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AssignProject getAssignProject(Integer projectId) {
        /**
         * 获取实验项目基本信息
         */
        AssignProject assignProject = experimentMapper.getAssignProject(projectId);
        /**
         * 获取所有选择题
         */
        List<ChoiceQuestion> choiceQuestion = choiceQuestionMapper.getChoiceQuestionByProjectId(projectId);
        /**
         * 获取所有的客观题
         */
        List<ObjectiveItem> objectiveItems = choiceQuestionMapper.getObjectiveItem(projectId);
        assignProject.setChoiceQuestions(choiceQuestion);
        assignProject.setObjectiveItems(objectiveItems);
        return assignProject;
    }


    @Override
    public ResultBean checkAssignStatus(Integer projectId) {
        /**
         * 0为未布置，1未改实验已经布置了
         *
         */
        int count=experimentMapper.checkAssignStatus(projectId);
        int assignStatus=0;
        if(count!=0){
            assignStatus=1;
        }
        return ResultBean.success(assignStatus);
    }


    @Override
    public ResultBean deleteProject(Integer projectId) {
        Integer deleteProjectStatus=experimentMapper.deleteProject(projectId);
        experimentMapper.deleteProjectShareTeacher(projectId);
        experimentMapper.deleteProjectTeacher(projectId);
        if(deleteProjectStatus!=0){
            redisCache.deleteObject("doExperiment:"+projectId);
            redisCache.deleteObject("searchExperiment:"+projectId);
            return ResultBean.success("成功删除实验");
        }else{
            return ResultBean.success("删除失败");
        }
    }


    @Override
    public ResultBean checkProjectAssign(Integer projectId) {
        List<SysUser> sysUserList=experimentMapper.checkProjectAssign(projectId);
        return ResultBean.success(sysUserList);
    }


    @Override
    public ResultBean deleteProjectMaterials(Integer learnId) {
        Integer deleteProjectMaterialsStatus=experimentMapper.deleteProjectMaterials(learnId);
        if(deleteProjectMaterialsStatus!=0){
            return ResultBean.success("成功删除文件资料");
        }else{
            return ResultBean.error("删除文件资料失败");
        }
    }

    @Override
    public void downloadProjectFile(Integer projectId,HttpServletRequest request,HttpServletResponse response) {
       RoProject project=experimentMapper.getProject(projectId);
       if(StringUtils.isNotEmpty(project.getFilePath())){
           try {
               fileUploadAndDownload.download(request,response,project.getFilePath());
           } catch (IOException e) {
               logger.error("下载文件失败{}",project.getFilePath());
               e.printStackTrace();
           }
       }
    }
}
